﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Xml;
using System.ServiceModel;
using System.IO;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Excel;


namespace DMSClient.Distributors
{ //
    public partial class Invoices : Form
    {

        private DMSServices.DMSServicesClient client;
        private DataTable dt;
        private DataTable dtOrderInvoice;
        private DataTable dtOrderInvoice_AUD;
        private DataTable dtInvoiceErrorReport;  

        string fileNameToExportPDF = "";
        static bool fileExported = false;
        private string ambient;
        private string idDistributor = "";
        private string cdDistributor = "";
        private string dtInvoiceStart = "";
        private string dtInvoiceEnd = "";
        DataSet ds = null;


        public Invoices()
        {
            InitializeComponent();
            this.ambient = Properties.Settings.Default.CurrentEnv;
            this.Text = this.ambient + " - Invoices Report";

            WSHttpBinding Binding = new WSHttpBinding();
            Binding.MaxReceivedMessageSize = Int32.MaxValue;
            Binding.MaxBufferPoolSize = Int32.MaxValue;
            Binding.CloseTimeout = TimeSpan.MaxValue;
            Binding.ReceiveTimeout = TimeSpan.MaxValue;
            Binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
            Binding.Security.Mode = SecurityMode.None;


            EndpointAddress address = new EndpointAddress(Properties.Settings.Default.Server);
            client = new DMSServices.DMSServicesClient(Binding, address);
            
        }

        private void Invoices_Load(object sender, EventArgs e)
        {
            uceDistributors.DisplayMember = "cdOrgUnit";
            uceDistributors.ValueMember = "idOrgUnit";

            string respuesta = client.getDistributorsList(this.ambient);

            dt = new DataTable("dtDistributorsList");
            dt.Columns.Add("idOrgUnit", Type.GetType("System.Int16"));
            dt.Columns.Add("cdOrgUnit", Type.GetType("System.String"));

            DataSet dataSet = new DataSet();
            dataSet.Tables.Add(dt);
            System.IO.StringReader xmlSR = new System.IO.StringReader(respuesta);
            dataSet.ReadXml(xmlSR, XmlReadMode.ReadSchema);
            xmlSR.Close();

            uceDistributors.DataSource = dt;
            uceDistributors.SelectedIndex = 0;
           
        }

        private void cargarGrid()
        {
             idDistributor = uceDistributors.Value.ToString();
             cdDistributor = uceDistributors.Text.ToString();
             dtInvoiceStart = udteStartDate.Value.ToString();
             dtInvoiceEnd = udteEndDate.Value.ToString();

             WSHttpBinding binding = new WSHttpBinding();
             binding.CloseTimeout = new TimeSpan(0, 1, 0);
             binding.OpenTimeout = new TimeSpan(0, 1, 0);
             binding.ReceiveTimeout = new TimeSpan(0, 10, 0);
             binding.SendTimeout = new TimeSpan(0, 1, 0);          
             binding.MaxReceivedMessageSize = Int32.MaxValue;
             binding.MaxBufferPoolSize = Int32.MaxValue;
             binding.ReaderQuotas.MaxArrayLength = Int32.MaxValue;
             binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
             binding.Security.Mode = SecurityMode.None;
          


             EndpointAddress address = new EndpointAddress(Properties.Settings.Default.Server);
             DMSServices.DMSServicesClient service = new DMSServices.DMSServicesClient(binding, address);
             DMSServices.DMSServicesClient serviceII = new DMSServices.DMSServicesClient(binding, address);

             string respuesta = null;
            //--DATOS FATURA
             try
             {
                 service.Open();
                 //"|1" para que el modo de consulta consulte por las fechas de INVOICES
                 respuesta = service.getOInvoiceReport(idDistributor + "|1", DateTime.Parse(dtInvoiceStart), DateTime.Parse(dtInvoiceEnd), this.ambient);                 
                 service.Close();
                 respuesta = Compression.Decompress(respuesta);

                 dtOrderInvoice = new DataTable("dtOInvoiceReport");
                 dtOrderInvoice.Columns.Add("cdOrder");
                 dtOrderInvoice.Columns.Add("cdCreationUser");
                 dtOrderInvoice.Columns.Add("cdStore");
                 dtOrderInvoice.Columns.Add("cdRegion");
                 dtOrderInvoice.Columns.Add("dtOrder");
                 dtOrderInvoice.Columns.Add("vlDiscountTotal",typeof(double));
                 dtOrderInvoice.Columns.Add("vlTotalOrder", typeof(double));
                 dtOrderInvoice.Columns.Add("vlTotalUnit", typeof(double));
                 dtOrderInvoice.Columns.Add("cdRoute");
                 dtOrderInvoice.Columns.Add("cdStatusOrder");
                 dtOrderInvoice.Columns.Add("cdInvoice");
                 dtOrderInvoice.Columns.Add("dsDisplayText");
                 dtOrderInvoice.Columns.Add("dtInvoice", typeof(DateTime));
                 dtOrderInvoice.Columns.Add("vlTotalInvoice", typeof(double));
                 dtOrderInvoice.Columns.Add("nrTotalQuantity", typeof(double));
                 dtOrderInvoice.Columns.Add("cdStatusInvoice");

                 DataSet dataSet = new DataSet("dsOInvoiceReport");
                 dataSet.Tables.Add(dtOrderInvoice);
                 System.IO.StringReader xmlSR = new System.IO.StringReader(respuesta);
                 dataSet.ReadXml(xmlSR, XmlReadMode.ReadSchema);
                 xmlSR.Close();
             }
             catch (Exception ex)
             {                 
                 throw new Exception(Properties.Settings.Default.DistributorsListErrorMsg, ex.InnerException);
             }
            
        
        }

        private void bgWorker_Consulta_DoWork(object sender, DoWorkEventArgs e)
        {
            cargarGrid();
        }

        private void uceDistributors_ValueChanged(object sender, EventArgs e)
        {
            ugOrderInvoive.DataSource = null;
            ug_interfaceView.DataSource = null;
            ugErrorReport.DataSource = null;
            ug_interfaceView.DataBind();
            ugErrorReport.DataBind();
            ugOrderInvoive.DataBind();
        }

        private void bgWorker_Consulta_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (!e.Cancelled && !this.IsDisposed)
            {
                //Datos de la vista completa o de interfaz                
                ug_interfaceView.DataSource = dtOrderInvoice;
                ug_interfaceView.DataBind();
                //Datos de las facturas
                ugOrderInvoive.DataSource = dtOrderInvoice;
                ugOrderInvoive.DataBind();
               

                try
                {
                    //Ocultando columnas de INVOICE pero que q tienen datos necesarios
                    ugOrderInvoive.DisplayLayout.Bands[0].Columns["cdOrder"].Hidden = false;
                    ugOrderInvoive.DisplayLayout.Bands[0].Columns["cdCreationUser"].Hidden = true;
                    ugOrderInvoive.DisplayLayout.Bands[0].Columns["cdStore"].Hidden = true;
                    ugOrderInvoive.DisplayLayout.Bands[0].Columns["cdRegion"].Hidden = true;
                    ugOrderInvoive.DisplayLayout.Bands[0].Columns["dtOrder"].Hidden = true;
                    ugOrderInvoive.DisplayLayout.Bands[0].Columns["vlDiscountTotal"].Hidden = true;
                    ugOrderInvoive.DisplayLayout.Bands[0].Columns["vlTotalOrder"].Hidden = true;
                    ugOrderInvoive.DisplayLayout.Bands[0].Columns["vlTotalUnit"].Hidden = true;
                    ugOrderInvoive.DisplayLayout.Bands[0].Columns["cdRoute"].Hidden = true;
                    ugOrderInvoive.DisplayLayout.Bands[0].Columns["cdStatusOrder"].Hidden = true;

                    ugOrderInvoive.DisplayLayout.Bands[0].Columns["vlDiscountTotal"].CellAppearance.TextHAlign = Infragistics.Win.HAlign.Right;
                    ugOrderInvoive.DisplayLayout.Bands[0].Columns["vlTotalOrder"].CellAppearance.TextHAlign = Infragistics.Win.HAlign.Right;
                    ugOrderInvoive.DisplayLayout.Bands[0].Columns["vlTotalUnit"].CellAppearance.TextHAlign = Infragistics.Win.HAlign.Right;
                    ugOrderInvoive.DisplayLayout.Bands[0].Columns["vlTotalInvoice"].CellAppearance.TextHAlign = Infragistics.Win.HAlign.Right;
                    ugOrderInvoive.DisplayLayout.Bands[0].Columns["nrTotalQuantity"].CellAppearance.TextHAlign = Infragistics.Win.HAlign.Right;

                }
                catch (Exception eee) 
                {
                    throw new Exception(Properties.Settings.Default.DistributorsListErrorMsg, eee.InnerException);
                }
                //-Reporte de auditoria                
                //ugAUD_Invoice.DataSource = dtOrderInvoice_AUD;
                //ugAUD_Invoice.DataBind();

                activarControles(true);
            }
            else if (e.Error != null) 
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, e.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    activarControles(true);
                }
            }
           
        }

        private void activarControles(bool value)
        {
            loader.Visible = !value;
            loader_errorReport.Visible = !value;
            ultraGroupBox1.Enabled = value;
            ugOrderInvoive.Enabled = value;
            uBtnLoadErrorReport.Enabled = value;
        }

        private void ultraButton1_Click(object sender, EventArgs e)
        {            
            //Verificamos consultas máximo para 3 meses para que no se pifie esta...
            int currenNrodays = 0;
            if (365 < (currenNrodays = DateTime.Parse(udteEndDate.Value.ToString()).Subtract(DateTime.Parse(udteStartDate.Value.ToString())).Days))
            {
                MessageBox.Show("Maximum range of dates to see: 12 months : 365 Days. Your selected: " + currenNrodays.ToString() + " Days.");
                return;
            }
            else if (currenNrodays <0 )
            {
                MessageBox.Show("Start date greater than end date.");
                return;
            }
            bgWorker_Consulta.RunWorkerAsync();
            activarControles(false);
        }


        private void bntExport_Click(object sender, EventArgs e)
        {
            

            if (ugOrderInvoive.Rows.Count < 1)
            {
                MessageBox.Show(this, "There is no data to export", "Invoice Report", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            if (MessageBox.Show(this, "The data will be exported interface view. Continue?", "Invoice Report", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                System.Windows.Forms.SaveFileDialog dialogo = new System.Windows.Forms.SaveFileDialog();
                dialogo.DefaultExt = "pdf";
                dialogo.Filter = ". pdf | (Pdf File)";
                if (dialogo.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    activarControles(false);
                    fileNameToExportPDF = dialogo.FileName;
                    bgWorker_Consulta.CancelAsync();
                    bgWorker_EXPORT.RunWorkerAsync();

                }
            }
            else
            {
                return;
            }                     
        }


        private void bgWorker_EXPORT_DoWork(object sender, DoWorkEventArgs e)
        {
            PDFExport d = new PDFExport(PDFExport_F);
            this.Invoke(d, new object[] { fileNameToExportPDF });
        }

        //Delegado para poder acceder a controles en el DoWork
        delegate void PDFExport(string nombreYrutaPDF);

        /*Exporta a PDF*/
        private void PDFExport_F(string nombreYrutaPDF)
        {
            loader.Visible = true;
            try
            {                                
                    //Reporte en formato PDF
                this.ultraGridDocumentExporter1.Export(ug_interfaceView, nombreYrutaPDF, Infragistics.Win.UltraWinGrid.DocumentExport.GridExportFileFormat.PDF);
                    //Reporte en formato TXT: Super mas lento por que toca recorrer el grid fila a fila
                    //exportTo_TXT(ugOrderInvoive);
                    fileExported = true;                              
            }
            catch (Exception Ex)
            {
                throw new Exception(Properties.Settings.Default.DistributorsListErrorMsg, Ex.InnerException);
            }
            return;
        }

        private void bgWorker_EXPORT_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (!this.IsDisposed)
            {
                activarControles(true);
                if (fileExported)
                {
                    fileExported = false;
                    System.Diagnostics.Process.Start(fileNameToExportPDF);
                }
            }
            else if (e.Error != null)
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, e.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    activarControles(true);
                }
            }
            
        }

        private void ugOrderInvoive_AfterSelectChange(object sender, Infragistics.Win.UltraWinGrid.AfterSelectChangeEventArgs e)
        {           
        }

        private void ugOrderInvoive_DoubleClick(object sender, EventArgs e)
        {
             Infragistics.Win.UltraWinGrid.UltraGrid grid = (Infragistics.Win.UltraWinGrid.UltraGrid)sender;
            Infragistics.Win.UIElement element = grid.DisplayLayout.UIElement.LastElementEntered;
            Infragistics.Win.UltraWinGrid.UltraGridCell cell = element.GetContext(typeof(Infragistics.Win.UltraWinGrid.UltraGridCell)) as Infragistics.Win.UltraWinGrid.UltraGridCell;

            if (cell != null)
            {                
                string[] dataHead = new string[13];
                //ENCABEZADOS DE LA ORDEN
                dataHead[0] = grid.ActiveRow.Cells["cdOrder"].Value.ToString(); //cod ERP    = cdOrder
                dataHead[1] = grid.ActiveRow.Cells["cdRegion"].Value.ToString();//region      = cdRegion
                dataHead[2] = grid.ActiveRow.Cells["vlDiscountTotal"].Value.ToString();//total descuento = vlDiscountTotal
                dataHead[3] = grid.ActiveRow.Cells["vlTotalOrder"].Value.ToString();//valor total     = vlTotalOrder
                dataHead[4] = grid.ActiveRow.Cells["dtOrder"].Value.ToString();//fecha Orden   =     dtOrder                
                dataHead[5] = grid.ActiveRow.Cells["cdStatusOrder"].Value.ToString();//estado orden  =      cdStatusOrder                
                dataHead[6] = grid.ActiveRow.Cells["vlTotalUnit"].Value.ToString();//numero total de lineas en la oren =  vlTotalUnit
                //ENCABEZADOS DE INVOICE                        
                dataHead[7] = grid.ActiveRow.Cells["cdInvoice"].Value.ToString(); //cod Documento   = cdInvoice
                dataHead[8] = grid.ActiveRow.Cells["dsDisplayText"].Value.ToString();//Descripcion     = dsDisplayText
                dataHead[9] = grid.ActiveRow.Cells["nrTotalQuantity"].Value.ToString();//total productos = nrTotalQuantity
                dataHead[10] = grid.ActiveRow.Cells["vlTotalInvoice"].Value.ToString();//valor total     = vlTotalInvoice
                dataHead[11] = grid.ActiveRow.Cells["dtInvoice"].Value.ToString();//fecha factura   = dtInvoice                     
                dataHead[12] = grid.ActiveRow.Cells["cdStatusInvoice"].Value.ToString();//estado factura   = dtInvoice                     
                //modoConsulta:
                //"|1" para que el modo de consulta consulte por las fechas de INVOICES
                //"|2" para que el modo de consulta consulte por las fechas de ORDERS 
                OrderInvoiceDetails frmDetails = new OrderInvoiceDetails(idDistributor, dtInvoiceStart, dtInvoiceEnd, dataHead[7].ToString().Trim(), ambient, dataHead,"1");              
                frmDetails.MdiParent = this.ParentForm;              
                frmDetails.Show();//.Show();
            }
        }

        private void Invoices_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (bgWorker_EXPORT.IsBusy)
            {
                bgWorker_EXPORT.CancelAsync();
            }
            
            if (bgWorker_Consulta.IsBusy)
            {
                bgWorker_Consulta.CancelAsync();
            }

            if (bgWorker_LoadErrorReport.IsBusy)
            {
                bgWorker_LoadErrorReport.CancelAsync();
            }
        }

        private void Invoices_Shown(object sender, EventArgs e)
        {
            loader.Left = (this.Width - loader.Width) / 2;
            loader.Top = ((this.Height - loader.Height) / 2) - loader.Height;
        }

        private void Invoices_Resize(object sender, EventArgs e)
        {
            loader.Left = (this.Width - loader.Width) / 2;
            loader.Top = ((this.Height - loader.Height) / 2) - loader.Height;
        }

        private void ugOrderInvoive_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            foreach (UltraGridBand bands in e.Layout.Bands)
            {
                foreach (UltraGridColumn ugc in bands.Columns)
                {
                    ugc.PerformAutoResize(PerformAutoSizeType.AllRowsInBand, true);
                }
            }
        }

        private void Invoices_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)27)
            {
                this.Close();
            }
        }

        private void ugOrderInvoive_InitializeRow(object sender, InitializeRowEventArgs e)
        {                        
            for (int i = 0; i < e.Row.Cells.Count; i++) 
            {
                e.Row.Cells[i].ToolTipText = "Double Click for Details";
            }            
        }

        private void ug_interfaceView_InitializeLayout(object sender, InitializeLayoutEventArgs e)
        {
            foreach (UltraGridBand bands in e.Layout.Bands)
            {
                foreach (UltraGridColumn ugc in bands.Columns)
                {
                    ugc.PerformAutoResize(PerformAutoSizeType.AllRowsInBand, true);
                }
            }
        }

        private void ug_interfaceView_InitializeRow(object sender, InitializeRowEventArgs e)
        {
            for (int i = 0; i < e.Row.Cells.Count; i++)
            {
                e.Row.Cells["cdOrder"].Appearance.BackColor = Color.SkyBlue;
                e.Row.Cells["cdInvoice"].Appearance.BackColor = Color.SkyBlue;
            }
        }

        private void ugErrorReport_InitializeLayout(object sender, InitializeLayoutEventArgs e)
        {
            foreach (UltraGridBand bands in e.Layout.Bands)
            {
                foreach (UltraGridColumn ugc in bands.Columns)
                {
                    ugc.PerformAutoResize(PerformAutoSizeType.AllRowsInBand, true);
                }
            }
        }

        private void uBtnLoadErrorReport_Click(object sender, EventArgs e)
        {
            bgWorker_LoadErrorReport.RunWorkerAsync();
            activarControles(false);          
        }

        //Delegado para poder acceder a controles en el DoWork del reporte de errores
        delegate void ErrorReporExport();

        private void cargarGridErrorReport()
        {
            //Validando que ya se halla consultado Invoices u Orders
            if (idDistributor.Trim().Equals("") || dtInvoiceStart.Trim().Equals("") || dtInvoiceEnd.Trim().Equals("")) 
            {
                MessageBox.Show(this, "To generate the report you should first generate the invoices report", "Although it is not possible to generate the report", MessageBoxButtons.OK, MessageBoxIcon.Error);
                ultraTabControl1.Tabs[0].Selected = true;   //.Active = true;
                return;
            }
                

            WSHttpBinding binding = new WSHttpBinding();
            binding.CloseTimeout = new TimeSpan(0, 1, 0);
            binding.OpenTimeout = new TimeSpan(0, 1, 0);
            binding.ReceiveTimeout = new TimeSpan(0, 10, 0);
            binding.SendTimeout = new TimeSpan(0, 1, 0);
            binding.MaxReceivedMessageSize = Int32.MaxValue;
            binding.MaxBufferPoolSize = Int32.MaxValue;
            binding.ReaderQuotas.MaxArrayLength = Int32.MaxValue;
            binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
            binding.Security.Mode = SecurityMode.None;

            EndpointAddress address = new EndpointAddress(Properties.Settings.Default.Server);            
            DMSServices.DMSServicesClient serviceII = new DMSServices.DMSServicesClient(binding, address);

            string respuesta = null;
            //--DATOS FATURA
            try
            {
                serviceII.Open();
                //"|ErrorReport" para que el modo de consulta el procedimiento que carga el reporte de errores
                respuesta = serviceII.getOItemsInvoiceReport(idDistributor + "|ErrorReport", DateTime.Parse(dtInvoiceStart), DateTime.Parse(dtInvoiceEnd), this.ambient);
                serviceII.Close();
                respuesta = Compression.Decompress(respuesta);

                dtInvoiceErrorReport = new DataTable("DT_ErrorsInvoiceDetailsInvoice");
                dtInvoiceErrorReport.Columns.Add("cdOrder");
                dtInvoiceErrorReport.Columns.Add("cdInvoice");
                dtInvoiceErrorReport.Columns.Add("vlTotalInvoice");
                dtInvoiceErrorReport.Columns.Add("SumDetailsInvoice");
                dtInvoiceErrorReport.Columns.Add("Differene_InvoiceDetailsInvoice");

                DataSet dataSet = new DataSet("DS_ErrorsInvoiceDetailsInvoice");
                dataSet.Tables.Add(dtInvoiceErrorReport);
                System.IO.StringReader xmlSR = new System.IO.StringReader(respuesta);
                dataSet.ReadXml(xmlSR, XmlReadMode.ReadSchema);
                xmlSR.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(Properties.Settings.Default.DistributorsListErrorMsg, ex.InnerException);
            }
        }

        private void bgWorker_LoadErrorReport_DoWork(object sender, DoWorkEventArgs e)
        {
            ErrorReporExport   d = new ErrorReporExport(cargarGridErrorReport);
            this.Invoke(d, new object[] {  });            
        }

        private void bgWorker_LoadErrorReport_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

            if (!e.Cancelled && !this.IsDisposed)
            {
                ugErrorReport.DataSource = dtInvoiceErrorReport;
                ugErrorReport.DataBind();
                activarControles(true);                
            }
            else if (e.Error != null) 
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, e.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    activarControles(true);
                }
            }           
        }

        private void ugErrorReport_InitializeRow(object sender, InitializeRowEventArgs e)
        {            
                try
                {
                    double doubleTMP = Math.Truncate(Double.Parse((e.Row.Cells["Differene_InvoiceDetailsInvoice"].Value.ToString().Trim())));
                    Int64 valueDiferenciaTotal = Int64.Parse(doubleTMP.ToString());
                    if (valueDiferenciaTotal != 0)
                    {
                        e.Row.Cells["Differene_InvoiceDetailsInvoice"].Appearance.BackColor = Color.LightPink;
                        e.Row.Cells["Differene_InvoiceDetailsInvoice"].ToolTipText = "Problem whit Invoice and Invoice Details....";
                    }
                }
                catch (Exception ee) 
                {
                    throw new Exception(Properties.Settings.Default.DistributorsListErrorMsg, ee.InnerException);
                }                  
        }
      
        private void exportTo_TXT(Infragistics.Win.UltraWinGrid.UltraGrid uggridToExport) 
        {
            string lineaAGuardar = "";

            try {                
                 foreach (UltraGridCell cell in uggridToExport.Rows[0].Cells)
                 {                    
                    lineaAGuardar += cell.Column.Key + "\t";//cell.Column.Header.Caption                    
                 }                
                 lineaAGuardar += "\n";

                 foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in uggridToExport.Rows)
                 {
                     for (int i = 0; i < row.Cells.Count; i++)
                     {
                         lineaAGuardar += row.Cells[i].Value.ToString() + "\t";
                     }
                     lineaAGuardar += "\n";
                 }
                 string tempFileName = Path.GetTempFileName();
                 StreamWriter writer = File.CreateText(tempFileName);
                 writer.Write(lineaAGuardar);
                 writer.Close();

                 System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                 startInfo.FileName = "wordpad.EXE"; //"notepad.EXE";//
                 startInfo.Arguments = Environment.GetEnvironmentVariable("TMP") + "\\" + Path.GetFileName(tempFileName).ToString(); //tempFileName;

                 if (MessageBox.Show(this, "Do you want to open the file?", "Data Successfully Exported", MessageBoxButtons.YesNo) == DialogResult.Yes)
                 {
                     System.Diagnostics.Process.Start(startInfo);
                 }                                    
            }
            catch (Exception ee) 
            {
                MessageBox.Show("Error "+ee.Message);
            }                            
        }

     


    }
}
